package com.deluxelx.soul.inn.service.search.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deluxelx.soul.inn.bean.search.History;
import com.deluxelx.soul.inn.common.util.RedisUtil;
import com.deluxelx.soul.inn.common.util.supportIds.SnowflakeId;
import com.deluxelx.soul.inn.mapper.search.HistoryMapper;
import com.deluxelx.soul.inn.service.search.HistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;

import static com.deluxelx.soul.inn.common.constant.HistoryConstant.buildHistoryKey;

/**
 * 搜索历史-接口实现类
 *
 * @author liaozihao
 * @date 2024-04-18 10:12
 */
@Service
@Slf4j
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Resource
    private SnowflakeId snowflake;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<History> fetchHistoryByUser(String userId) {
        if (StrUtil.isBlank(userId)) {
            log.error("fetchHistoryByUser方法错误：userId为空");
            return Collections.emptyList();
        }
        // 因为这个缓存是永久保存的，所以这里不需要判断缓存是否存在
        return redisUtil.rangeAllByScoreDesc(buildHistoryKey(userId), History.class);
    }

    @Override
    public Boolean addHistory(History history) {
        LocalDateTime now = LocalDateTime.now();
        String key = buildHistoryKey(history.getUserId());
        history.setDeleteFlag(0);
        String historyJson = JSONObject.toJSONString(history);
        double score = now.toInstant(ZoneOffset.UTC).toEpochMilli();
        if (redisUtil.score(key, historyJson) == null) {
            history.setId(snowflake.nextStrId());
            return redisUtil.addZset(key, historyJson, score);
        } else {
            return redisUtil.replaceScore(key, historyJson, score);
        }
    }

    @Override
    public Boolean deleteHistory(String userId) {
        if (StrUtil.isBlank(userId)) {
            log.error("fetchHistoryByUser方法错误：userId为空");
            return Boolean.FALSE;
        }
        String key = buildHistoryKey(userId);
        redisUtil.del(key);
        return this.lambdaUpdate()
                .eq(History::getUserId, userId)
                .set(History::getDeleteFlag, 1)
                .update();
    }
}
